package cn.gcjxsc.messaging.sink;

import cn.gcjxsc.consts.ErrorType;
import cn.gcjxsc.entity.mall.BaseOrder;
import cn.gcjxsc.service.common.ErrorService;
import cn.gcjxsc.service.integral.IncomeService;
import cn.gcjxsc.service.mall.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.messaging.Message;
import org.springframework.util.StringUtils;

/**
 * @author pumbaa
 * @since 1.0
 */
@EnableBinding(OrderShippedSink.class)
public class SalesmanIntegralSink {

    private Logger logger = LoggerFactory.getLogger(SalesmanIntegralSink.class);
    @Autowired
    private IncomeService incomeService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private ErrorService errorService;

    /**
     * 接收订单完成事件
     *
     * @param message 消息
     */
    @StreamListener(OrderShippedSink.QUE_NAME)
    public void process(Message<String> message) {
        String sn = message.getPayload();
        if (StringUtils.isEmpty(sn)) {
            logger.error("订单号为空");
            return;
        }
        BaseOrder order = orderService.findShoppingOrderBySn(sn);
        IncomeService.BindingResult bindingResult = new IncomeService.BindingResult();
        incomeService.checkOrder(order, bindingResult);
        if (bindingResult.getErrorCount() > 0) {
            logger.error(bindingResult.getMsg() + "订单号:{}", sn);
            return;
        }
        if (incomeService.isFlagged(sn)) {
            logger.error("该订单已计算收益.{}", sn);
            return;
        }
        try {
            incomeService.processShoppingOrderDone(order);
        } catch (Exception e) {
            e.printStackTrace();
            try {
                errorService.recordError(e, ErrorType.SALESMAN_SHOPPING_INCOME);
            } catch (Exception e1) {
                e1.printStackTrace();
                logger.error("计算收益失败.订单号[{}]\n{}", sn, errorService.recordTrace(e));
            }
        }
    }
}
